package com.codeworker.app.ui.wrapper;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.codeworker.app.R;

/**
 * https://www.ab62.cn/article/18902.html
 */
public class MyLoading {

    private static Dialog loadingDialog;

    /**
     * 显示Dialog
     *
     * @param context      上下文对象
     */
    public static void showLoadDialog(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        @SuppressLint("InflateParams") View v = inflater.inflate(R.layout.layout_common_loading, null);
        LinearLayout layout =  v.findViewById(R.id.dialog_bg);

        // main.xml中的ImageView
        ImageView loadImage = (ImageView) v.findViewById(R.id.load_iv);
        // 加载动画
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(context, R.anim.rotating_animation);
        // 使用ImageView显示动画
        loadImage.startAnimation(hyperspaceJumpAnimation);
        loadingDialog = new Dialog(context, R.style.TransDialogStyle);
        loadingDialog.setContentView(layout);
        loadingDialog.setCancelable(false);
        loadingDialog.setCanceledOnTouchOutside(false);


        Window window = loadingDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        window.setWindowAnimations(R.style.PopWindowAnimStyle);
        loadingDialog.show();
        loadingDialog.setOnKeyListener((dialog, keyCode, event) -> event.getKeyCode() == KeyEvent.KEYCODE_BACK);
    }

    /**
     * 关闭dialog
     */
    public static void closeDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

}
